import 'dart:developer';
import 'dart:io';

//socket管理界面
class SocketServerManage {
  static SocketServerManage? _instance;

  SocketServerManage._internal();

  factory SocketServerManage() {
    _instance ??= SocketServerManage._internal();
    return _instance!;
  }

  Socket? _socket;
  //数据回调
  Function? _onDataListener;

  // 建立连接
  void connectSocket(
      {String address = "123.162.182.159", int port = 12345}) async {
    await Socket.connect(
      address,
      port,
      timeout: const Duration(seconds: 5),
    ).then((Socket socket) {
      _socket = socket;
      _socket?.listen(onData,
          onError: onError, onDone: onDone, cancelOnError: false);
      //writeData("login sn6 88888888");
      //writeData("query q30mb 37118778172696567268"); // 订阅流
    }).catchError((e) {
      log("Unable to connect: $e");
      connectSocket(); // 连接超时，重新建立连接
    });
  }

  //接收数据
  onData(event) {
    log('socket: ${String.fromCharCodes(event)}');
    if (_onDataListener != null) {
      _onDataListener!(event);
    }
  }

  //回调错误信息
  onError(e) {
    log('${_socket?.address} --- ${e.toString()}');
  }

  //断开连接
  onDone() {
    log("---onDone---");
    Future.delayed(const Duration(milliseconds: 200), () {
      connectSocket(); // 重新建立连接
    });
  }

  // 发数据
  writeData(Object object, Function? function) {
    _onDataListener = function;
    _socket?.write(object);
  }

  // 关闭流通道
  socketClose() {
    _socket?.close();
  }
}
